<?php

namespace App\Lib\Tool;
//use Home\Model\File\File\FilePicModel;


class Tool {
     
    
    /**
     * 获取页面参数-过滤tink参数
     * @param type $name
     * @param string $default
     * @return string
     */
    public static function para($name,$default='') 
    {
        $data= I($name,$default=''); 
        if(is_array($data)){
            $datas=array();
            foreach ($data as  &$v) {
               $v=Tool::lib_replace_end_tag($v);
            }
            return $data;
        }else{
           return Tool::lib_replace_end_tag($data);
        }
        return $default;
    }
     
    /*
     * 循环检测并创建文件夹
     */ 
    public static function createDir($path) {
        if (!file_exists($path)) {
            self::createDir(dirname($path));
            mkdir($path, 0777);
        }
    }

    /*
     * 创建GUID
     */ 
    function getGuid() {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45); // "-"
        $uuid = ''
                . substr($charid, 0, 8) . $hyphen
                . substr($charid, 8, 4) . $hyphen
                . substr($charid, 12, 4) . $hyphen
                . substr($charid, 16, 4) . $hyphen
                . substr($charid, 20, 12);

        return $uuid;
    }  
    /**
     * html 入口
     * @param type $content
     * @param type $default
     * @return type
     */
    public static function ParaHtmlspecialchars($content,$default='')
    {
          return htmlspecialchars(stripslashes($content));
    } 
    /**
     * html 出口
     * @param type $content
     * @return type
     */
    public static function ParaHtmlpecialchars_decode($content)
    {
        return  htmlspecialchars_decode($content); 
    }
    /*
     * 获取参数，获取checkbox的值
     */
    public static function paraArr($para) {
        $arr_list = isset($_POST[$para]) ? $_POST[$para] : '';
        $arr_list = is_array($arr_list) ? implode(',', $arr_list) : $arr_list;
        $arr_list = $arr_list == '' ? '' : (',' . $arr_list . ','); 
        return $arr_list;
    }

    /*
     * 获取列表指定项的值
     */
    public static function getListItemValue($list, $id, $field = 'name') {
        $value = '';
        foreach ($list as $r) {
            if ($r['id'] == $id) {
                $value = $r[$field];
                break;
            }
        }

        return $value;
    }

    /*
     * 获取列表指定项
     */
    public static function getListItem($list, $id) {
        $value = NULL;
        foreach ($list as $r) {
            if ($r['id'] == $id) {
                $value = $r;
                break;
            }
        } 
        return $value;
    } 
    /*
     * MD5加密
     */
    public static function md5($str, $pre = '') {
        return md5($pre . '$$xxCC**`I1l0oOs5S~`..ERASDjkA^&*,.' . $str . '@x^#^$#@@&~!@~5+-/!@.');
    }

    /*
     * MD5_base64加密
     */
    function md5Base64($data, $pre = '') {
        return preg_replace('/=+$/', '', base64_encode(pack('H*', self::md5($data, $pre))));
    }
    
    /*
     * 返回时间长度
     */
    public static function formatTimeLong($second) {
        $bo = true;
        if ($second < 0) {
            $bo = false;
        }
        $second = abs($second);
        if ($second == 0) {
            return '0秒';
        }
        $str = '';
        $tmp = floor($second / (24 * 60 * 60));
        $second = $second % (24 * 60 * 60);
        if ($tmp > 0) {
            $str .= $tmp . '天';
        }
        $tmp = floor($second / (60 * 60));
        $second = $second % (60 * 60);
        if ($tmp > 0) {
            $str .= $tmp . '小时';
        }
        $tmp = floor($second / 60);
        $second = $second % 60;
        if ($tmp > 0) {
            $str .= $tmp . '分钟';
        }
        $tmp = $second;
        if ($tmp > 0) {
            $str .= $tmp . '秒';
        }

        if (!$bo) {
            $str = '-' . $str;
        }

        return $str;
    } 
    
    /*
     * 获取日期
     */

    public static function getDay($span_day = 0) {
        $day = date("Y-m-d");

        $span_day = intval($span_day);
        if ($span_day != 0) {
            $day = date("Y-m-d", strtotime($day) + 60 * 60 * 24 * $span_day);
        }

        return $day;
    }

    /**
     * 是否是当天
     * @param type $date
     * @return boolean
     */
    public static function isToday($date) {
        // 拟设一个日期
        //$a = '2012-06-28 10:10:10';
        // 转换为时间戳
        $a_ux = strtotime($date);
        // 转换为 YYYY-MM-DD 格式
        $a_date = date('Y-m-d', $a_ux);
        // 获取今天的 YYYY-MM-DD 格式
        $b_date = date('Y-m-d');
        // 使用IF当作字符串判断是否相等
        if ($a_date == $b_date) { 
            return $b_date;
        } else { 
            return false;
        }
    } 
    /**
     * 时间戳转 日期
     * @param type $time 时间戳
     */
    public static function getDate($time)
    {
          $date= date("Y-m-d H:i:s",  intval($time));
          return $date;
    }


    /*
     * 获取日期的偏移
     */ 
    public static function addDay($day, $span_day) {
        $span_day = intval($span_day);
        if ($span_day != 0) {
            $day = date("Y-m-d", strtotime($day) + 60 * 60 * 24 * $span_day);
        }

        return $day;
    }

    /*
     * 格式化URL
     */
    public static function formatUrl($url) {
        if (strpos(strtolower($url), 'http') !== 0) {
            $url = 'http://' . $url;
        } 
        return $url;
    } 

    /*
     * 获取当前时间戳(小数为毫秒)
     */ 
    public static function msTime() {
        return round(microtime(TRUE), 3);
    }

    /*
     * 获取当前时间(完整字符串形式)
     */ 
    public static function now() {
        return date('Y-m-d H:i:s', time());
    }

    /*
     * 避免HTML潜入
     */ 
    public static function html($content) {
        return htmlspecialchars(stripslashes($content));
    }

    /*
     * 避免HTML潜入 (取出空格、回车)
     */ 
    public static function htmlShort($content) {
        $content = htmlspecialchars(stripslashes($content));
        $content = str_replace(' ', '', $content);
        $content = str_replace('　', '', $content);
        $content = str_replace("\r", "\n", $content);
        $content = str_replace("\n", '', $content);

        return $content;
    } 
     
    public static function lib_replace_end_tag($str) {
        if (empty($str))
            return false;
        $str = htmlspecialchars($str);
        $str = str_replace('/', "", $str);
        $str = str_replace('.', "", $str);
        $str = str_replace("\\", "", $str);
        $str = str_replace("&gt", "", $str);
        $str = str_replace("&lt", "", $str);
        $str = str_replace("<SCRIPT>", "", $str);
        $str = str_replace("</SCRIPT>", "", $str);
        $str = str_replace("<script>", "", $str);
        $str = str_replace("</script>", "", $str);
        $str = str_replace("select", "", $str);
        $str = str_replace("join ", "", $str);
        $str = str_replace("union ", "", $str);
        $str = str_replace("where ", "", $str);
        $str = str_replace("insert ", "", $str);
        $str = str_replace("delete ", "", $str);
        $str = str_replace("update ", "", $str);
        $str = str_replace("like ", "", $str);
        $str = str_replace("drop ", "", $str);
        $str = str_replace("create ", "", $str);
        $str = str_replace("modify ", "", $str);
        $str = str_replace("rename ", "", $str);
        $str = str_replace("alter ", "", $str);
        $str = str_replace("cas ", "cast", $str);
        $str = str_replace("&", "&", $str);
        $str = str_replace(">", "", $str);
        $str = str_replace("<", "", $str);
        $str = str_replace(" ", chr(32), $str);
        $str = str_replace(" ", chr(9), $str);
        $str = str_replace("    ", chr(9), $str);
        $str = str_replace("&", chr(34), $str);
        $str = str_replace("'", chr(39), $str);
    //   $str = str_replace("<br />", chr(13), $str);
        $str = str_replace("''", "", $str);
        $str = str_replace("css", "", $str);
        $str = str_replace("CSS", "", $str);
        $str = str_replace("(", "", $str);
        $str = str_replace(")", "", $str);
        $str = str_replace("and", "", $str);
        
 
        //特殊字符 //| &  ; $ % @ ' " \' \" <> () + CR LF, \
        $str = str_replace("|", "", $str);
        $str = str_replace("&", "", $str);
        $str = str_replace(";", "", $str);
        $str = str_replace("$", "", $str);
        $str = str_replace("%", "", $str);
        $str = str_replace("@", "", $str);
        $str = str_replace("%", "", $str);
        $str = str_replace("'", "", $str);
        $str = str_replace("\"", "", $str);
        $str = str_replace("\\", "", $str);
        $str = str_replace("<>", "", $str);
        $str = str_replace("()", "", $str);
        $str = str_replace("+", "", $str);
        $str = str_replace("CR", "", $str);
        $str = str_replace("LF", "", $str);
        $str = str_replace(",", "", $str);
        $str = str_replace("\'", "", $str);
        
        //php
        $str = str_replace("php", "", $str);
        $str = str_replace("<? ", "", $str);
        $str = str_replace("?> ", "", $str);
        
        
        
        return $str;
    }

    
    //获取图片路径
    public static function getImageUrl($id){
        Constant::init();
        $file =new FilePicModel();
        $pic_max_datas = $file->getPicDatas($id);
        $max_img_url = getFullPicUrl($pic_max_datas);
        unset($file);
        return SYS_SER_IMAGE_DF_PATH.$max_img_url[0];
    }
    
    //模拟get提交
    
    public static function curlGet($url){
        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $result=curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    //模拟post提交
    public static function curlPost($data,$url){
        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  http_build_query($data));
        $result=curl_exec($ch);
        curl_close($ch); 
        
        return $result;
    }
    
    //模拟post提交
    public static function https_curlPost($data,$url){
        
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS,  http_build_query($data));
        $result = curl_exec($curl); // 执行操作
    
        return $result;
    }
    
    
    //查询物流的方法
    /*
     *
     * */
    public static function logistics($code,$nums){
    
        $attr=array();
        $url = "http://www.kuaidi100.com/query";
        $url .="?type={$code}&postid={$nums}&id=1&valicode=&temp=0.".time();
        $res = file_get_contents($url);
        $res=json_decode($res);
        $res=$res->data;
        if($res){
            foreach($res as $k=>$e){
                $attr[$k]['time']=$e->time;
                $attr[$k]['context']=$e->context;
            }
        }
        return $attr;
    }


    //查询ip地理位置的方法
    public static function ipAdress($ip){

        $url = 'http://ip-api.com/json/'.$ip.'?lang=zh-CN';

        $content = file_get_contents($url);

        $content = json_decode($content,true);

        if($content['status'] == 'fail'){
            return ['未获取','未获取','未获取'];
        }else{
            return [$content['country'].$content['city'],$content['lat'],$content['lon']];
        }

    }


    //获取域名 http
    public static function getHost(){

        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        return $http_type . $_SERVER['HTTP_HOST'];

    }

    //模拟post提交
    public static function http_post_json($json,$url) {

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);  //这两行一定要加，不加会报SSL 错误
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $response = curl_exec($ch);
        $errno = curl_errno($ch);
        $errmsg = curl_error($ch);
        curl_close($ch);

        $data = json_decode($response, true);

        return $data;
    }

    //查找最新数据的方法
    public static function arraySort($arr,$key,$type='asc'){

        $keyArr = []; // 初始化存放数组将要排序的字段值
        foreach ($arr as $k=>$v){
            $keyArr[$k] = $v[$key]; // 循环获取到将要排序的字段值
        }
        if($type == 'asc'){
            asort($keyArr); // 排序方式,将一维数组进行相应排序
        }else{
            arsort($keyArr);
        }
        foreach ($keyArr as $k=>$v){
            $newArray[$k] = $arr[$k]; // 循环将配置的值放入响应的下标下
        }
        $newArray = array_merge($newArray); // 重置下标
        return $newArray[0]; // 数据返回
    }

    //二位数组去重
    public static function  multi_array_unqie($arr){
        $data = array();
        foreach ($arr as $val){
            if(!in_array($val,$data)){
                $data[] = $val;
            }
        }
        return $data;
    }

    //记录苹果支付 主动调接口的日志
    public static  function  write ($prefix = '',$str = ''){

        $fileName = EASYSWOOLE_ROOT."/Log/task/address/".date("Y-m-d").'.txt';

        $prefix = "\n\ntitle:".$prefix."\t\n";
        $time = "time:".date("Y-m-d H:i:s")."\t\n";
        $conent = "content:".$str."\t\n";
        $spiltLine = '-------------------------------- line --------------------------------------';

        file_put_contents($fileName, $prefix.$time.$conent.$spiltLine, FILE_APPEND);

    }


}
